package com.wk.controller.student;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wk.pojo.*;
import com.wk.service.Courseservice;
import com.wk.service.Itemservice;
import com.wk.utils.PaginationConstant;
import com.wk.utils.responseresult;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.sql.Timestamp;
import java.util.*;

/**
 * @program: thesis
 * @description: 学生的课程类
 * @author: 王侃
 * @create: 2020-03-09 11:55
 **/
@Controller
public class Stucoursescontroller {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    Courseservice courseservice;
    @Autowired
    Itemservice itemservice;

    //返回课程的类型
    @ModelAttribute("coursetypes")
    public List<Coursetype> coursetypes()
    {
        List<Coursetype> coursetypes=courseservice.selectbyalltype();
        return coursetypes;
    }

    //展现出该课程的视频和习题
    @RequestMapping("/course/show/{id}")
    public String courseshow(@PathVariable("id") Integer id, Model model)
    {
        //通过课程的id号查出该课程的在线习题
        List<Map<String,Object>> radios=courseservice.selectbyradio(id);
        model.addAttribute("radios",radios);

        //通过课程的id号查出该课程的视频
        String path=courseservice.selectbyvideo(id);
        model.addAttribute("path",path);

        //通过课程id查出该课程的资料
        List<Course_data> datas=courseservice.selectbyalldatas(id);
        model.addAttribute("datas",datas);

        model.addAttribute("id",id);
        return "student/course/course_show";
    }

    //处理课程的习题提交
    @RequestMapping("/course/exam/submit/{id}")
    public String examsubmit(@RequestParam Map<String,String> map, @PathVariable("id")Integer id, Model model)
    {
        Set<String> set=map.keySet();//用来获取题目的id号,所以id号为String
        Iterator<String> iterator=set.iterator();//必需的

        Integer totalnumber=0;//答对数量
        Integer truenumber=0;//总题目
        float accurancy;//正确率


        while (iterator.hasNext())
        {
            String key= iterator.next();
            String value=map.get(key);//例如：获取题号为1的选项内容为A

            //通过主键id获得该题目信息
            Course_exam exam=courseservice.selectbyid(key);

            totalnumber++;
            if (exam.getAnswer_true().equals(value))
            {
                truenumber++;
            }
            else
            { }
        }

        //通过课程的id号查出该课程的在线习题
        List<Map<String,Object>> radios=courseservice.selectbyradio(id);
        model.addAttribute("radios",radios);

        //返回正确率
//        accurancy=(float)truenumber/totalnumber;

        model.addAttribute("totalnumber",totalnumber);
        model.addAttribute("truenumber",truenumber);

        return "student/course/course_examresult";
    }

    //跳转到课程习题管理界面
    @RequestMapping("/stu/center/course_test/list")
    public String course_list(Integer page, HttpSession session, Model model)
    {
        User user=(User)session.getAttribute("loginuser");

        //使用分页插件
        //        对第一次传值进行判断
        if (ObjectUtils.isEmpty(page)) {
            page = PaginationConstant.CURRENT_NUM;
        }
        //设置分页
        PageHelper.startPage(page, PaginationConstant.PAGE_SIZE);
        List<Course_exam> exams=courseservice.selectbyuser_exam(user.getId());
        PageInfo<Course_exam> pageInfo=new PageInfo<>(exams);
        model.addAttribute("pageinfo", pageInfo);
        //获得该用户的所有课程
        List<Course_topic> topics=courseservice.selectbytopiclist(user.getId(),"");
        model.addAttribute("tests",topics);
        return "student/course/course_test";
    }

    //跳转到课程习题添加界面
    @RequestMapping("/stu/center/course_test/add")
    public String course_add(HttpSession session,Model model)
    {
        //获得该用户的所有课程
        User user=(User)session.getAttribute("loginuser");
        List<Course_topic> topics=courseservice.selectbytopiclist(user.getId(),"");
        model.addAttribute("tests",topics);
        return "student/course/course_test_add";
    }

    //课程习题完成添加进行提交
    @RequestMapping("/stu/center/course_test/addsubmit")
    public String addsubmit(Course_exam exam,HttpSession session)
    {
        User user=(User)session.getAttribute("loginuser");

        exam.setUser_id(user.getId());
        exam.setType_id(1);//固定为单选题
        //获得该课程属于哪一个章节
        Course_topic topic=courseservice.selectbytopicall(exam.getCourse_id());
//        System.out.println(topic.getCoursetype_id());
        exam.setCoursetype_id(topic.getCoursetype_id());
        //并且让这一类型的题目数量加一
        courseservice.updatebyitemtype(1);
        //存入数据库
        courseservice.insertintocourse_exam(exam);

        return "common/success";
    }

    //修改课程习题前先显示出来,通过主键id显示课程测试
    @RequestMapping("/stu/center/course_test/getinformation")
    public String test_information(String id,Model model,HttpSession session)
    {
        Integer ID=Integer.parseInt(id);
        Course_exam exam=courseservice.selectbyid(id);
        model.addAttribute("exam",exam);

        //获得该用户的所有课程
        User user=(User)session.getAttribute("loginuser");
        List<Course_topic> topics=courseservice.selectbytopiclist(user.getId(),"");
        model.addAttribute("tests",topics);
        return "student/course/coursetest_update";
    }

    //修改课程测试并且提交
    @RequestMapping("/stu/center/course_test/updatesubmit")
    public String test_updatesubmit(Course_exam exam)
    {
        courseservice.updatebycourseexam(exam);
        return "common/success";
    }

    //跳转到课程发布界面
    @RequestMapping("/stu/center/release_course")
    public String release_course()
    {
        return "student/course/release_course";
    }

    //提交发布课程
    @RequestMapping("/stu/center/course/submit")
    public String course_submit(HttpSession session, String course_name, MultipartFile course_image, MultipartFile course_video, Integer coursetype_id)
    {
        logger.info("============>文件上传");
        //上传图片和视频到阿里云oss中，并且获得存储时的路径
        String video=courseservice.upload(course_video);
        String image=courseservice.upload(course_image);

        User user=(User)session.getAttribute("loginuser");
        //封装成类
        Course_topic topic=new Course_topic();
        topic.setCourse_image(image);
        topic.setCourse_video(video);
        topic.setCourse_name(course_name);
        topic.setCoursetype_id(coursetype_id);
        topic.setCreatetime(new Timestamp(new Date().getTime()));
        topic.setUser_id(user.getId());
        topic.setUsername(user.getUsername());
        topic.setPraise(0);
        //存入数据库
        courseservice.insertintotopic(topic);
        return "common/success";
    }

    //显示已发布课程的管理
    @RequestMapping("/stu/center/coursetopic/list")
    public String coursetopic_list(String course_name,Integer page,HttpSession session, Model model)
    {
        User user=(User)session.getAttribute("loginuser");
        //使用分页插件
        //        对第一次传值进行判断
        if (ObjectUtils.isEmpty(page)) {
            page = PaginationConstant.CURRENT_NUM;
        }
        //设置分页
        PageHelper.startPage(page, PaginationConstant.PAGE_SIZE);
        //不仅要传入当前页的值，还要传入查找的值
        List<Course_topic> list=courseservice.selectbytopiclist(user.getId(),course_name);
        PageInfo<Course_topic> pageInfo=new PageInfo<>(list);

        model.addAttribute("pageinfo", pageInfo);
        model.addAttribute("course_name",course_name);

        return "student/course/coursetopic_management";
    }

    //通过主键id删除课程
    @RequestMapping("/stu/center/coursetopic/delete")
    public String delete_coursetopic(String id)
    {
        Integer ID=Integer.parseInt(id);

        //在阿里云的oss删除对应的文件
        Course_topic topic=courseservice.selectbytopicall(ID);
        courseservice.deletealiyunoss(topic.getCourse_image());
        courseservice.deletealiyunoss(topic.getCourse_video());

        //删除该课程的随堂测试
        courseservice.deletebycourseexam(ID);
        //删除该课程的topic内容
        courseservice.deletebycoursetopic(ID);


        return "common/success";
    }

    //在更新课程信息时，通过主键id显示课程信息
    @RequestMapping("/stu/center/coursetopic/getinformation")
    @ResponseBody
    public responseresult getinformation(String id)
    {
        Integer ID=Integer.parseInt(id);
        //获取到信息
        Course_topic topic=courseservice.selectbytopicall(ID);
        return responseresult.success(topic);
    }

    //更新课程信息实现上传
    @RequestMapping("/stu/center/coursetopic/update")
    public String topicupdate(HttpSession session,String id,String course_name, MultipartFile course_image, MultipartFile course_video, Integer coursetype_id)
    {
        Integer ID=Integer.parseInt(id);
        //在阿里云的oss删除对应的文件
        Course_topic topic2=courseservice.selectbytopicall(ID);
        courseservice.deletealiyunoss(topic2.getCourse_image());
        courseservice.deletealiyunoss(topic2.getCourse_video());
        //上传图片和视频到阿里云oss并且获得路径
        String video=courseservice.upload(course_video);
        String image=courseservice.upload(course_image);
        User user=(User)session.getAttribute("loginuser");
        //封装成类
        Course_topic topic=new Course_topic();
        topic.setId(ID);
        topic.setCourse_image(image);
        topic.setCourse_video(video);
        topic.setCourse_name(course_name);
        topic.setCoursetype_id(coursetype_id);
        topic.setCreatetime(new Timestamp(new Date().getTime()));
        topic.setUser_id(user.getId());
        topic.setUsername(user.getUsername());
        //数据库更新
        courseservice.updatebycoursetopic(topic);
        return "common/success";
    }

    //播放自己的视频
    @RequestMapping("/stu/center/mycourse_video")
    public String mycourse_video(String video,Model model)
    {
        model.addAttribute("video",video);
        return "common/mycourse_video";
    }

    //通过主键id删除课程习题
    @RequestMapping("/stu/center/course_test/delete")
    public String test_delete(String id)
    {
        Integer ID=Integer.parseInt(id);
        Course_exam exam=courseservice.selectbyid(id);
        //并且让该类型课程数量减一
        itemservice.deletebyitemtype(exam.getType_id());

        courseservice.deletebycoursetestid(ID);

        return "common/success";
    }



    //用户课程点赞提交
    @RequestMapping("/stu/course_topic/praise")
    @ResponseBody
    public responseresult topic_praise(Integer praise,Integer myid)
    {
        Integer praise2=praise+1;
        courseservice.updatecoursepraise(myid,praise2);
        return responseresult.success();
    }

    //用户评论点赞提交
    @RequestMapping("/stu/course/comment/praise")
    @ResponseBody
    public responseresult comment_praise(Integer commentpraise)
    {
        courseservice.updatecommentpraise(commentpraise);
        return responseresult.success();
    }

    //返回课程评论界面
    @RequestMapping("/course/comment/{id}")
    public String course_comment(@PathVariable("id")Integer id,Model model)
    {
        //通过主键id查找该课程信息内容
        Course_topic topic=courseservice.selectbytopicall(id);
        model.addAttribute("topic",topic);
        //通过课程id查找出对应的课程评论
        List<Course_comment> comments=courseservice.selectbyidcomment(id);
        model.addAttribute("comments",comments);
        //通过课程id查找出对应的课程评论数
        String countcomment=courseservice.selectbycountcomment(id);
        model.addAttribute("countcomment",countcomment);
        model.addAttribute("course_id",id);
        return "student/course/course_comment";
    }

    //删除用户自己的评论
    @RequestMapping("/stu/course/comment/delete/{course_id}/{comment_id}")
    public String comment_delete(@PathVariable("course_id") Integer course_id,@PathVariable("comment_id") Integer comment_id)
    {
        courseservice.deletebyidcourse_comment(comment_id);
        return "redirect:/course/comment/"+course_id;
    }

    //发表课程评论
    @RequestMapping("/stu/course/commentsubmit")
    public String commentsubmit(HttpSession session,Course_comment comment)
    {
        User user=(User)session.getAttribute("loginuser");
        comment.setUser_id(user.getId());
        comment.setUser_name(user.getUsername());
        //存入数据库
        comment.setCreatetime(new Timestamp(new Date().getTime()));
        comment.setPraise(0);
        courseservice.insertintocoursecomment(comment);
        return "redirect:/course/comment/"+comment.getCourse_id();
    }

    //根据不同的课程类型显示,并且按照点赞顺序排序
    @RequestMapping("/course/type_show/{id}")
    public String course_typeshow(@PathVariable("id") String id,Integer page,String course_name, Model model)
    {
        //使用分页插件
        //对第一次传值进行判断
        if (ObjectUtils.isEmpty(page)) {
            page = PaginationConstant.CURRENT_NUM;
        }
        if(!id.equals("0"))
        {
            //设置分页
            PageHelper.startPage(page, PaginationConstant.PAGE_SIZE);
            List<Course_topic> topics=courseservice.selectbytypecourse(id,course_name);
            PageInfo<Course_topic> pageInfo=new PageInfo<>(topics);

            Coursetype coursetype=courseservice.selectbycoursetypeid(id);
            model.addAttribute("pageinfo",pageInfo);
            model.addAttribute("typename",coursetype.getCourse_name());
            model.addAttribute("course_name",course_name);
        }
        else
        {
            //设置分页
            PageHelper.startPage(page, PaginationConstant.PAGE_SIZE);
            List<Course_topic> topics=courseservice.selectbyallcoursetopic(course_name);
            PageInfo<Course_topic> pageInfo=new PageInfo<>(topics);

            model.addAttribute("pageinfo",pageInfo);
            model.addAttribute("typename","全部课程");
            model.addAttribute("course_name",course_name);
        }
        model.addAttribute("type_id",id);
        return "student/course/coursetopic_type";
    }

    //按照时间顺序排序
    @RequestMapping("/course/type_show/datetime/{id}")
    public String type_datetime(@PathVariable("id") String id, Integer page,String course_name, Model model)
    {
        Integer ID=Integer.parseInt(id);
        //使用分页插件
        //对第一次传值进行判断
        if (ObjectUtils.isEmpty(page)) {
            page = PaginationConstant.CURRENT_NUM;
        }
        if(!id.equals("0"))
        {
            //设置分页
            PageHelper.startPage(page, PaginationConstant.PAGE_SIZE);
            List<Course_topic> topics=courseservice.selectbydate_topic(ID,course_name);
            PageInfo<Course_topic> pageInfo=new PageInfo<>(topics);

            Coursetype coursetype=courseservice.selectbycoursetypeid(id);
            model.addAttribute("pageinfo",pageInfo);
            model.addAttribute("typename",coursetype.getCourse_name());
            model.addAttribute("course_name",course_name);
        }
        else
        {
            //设置分页
            PageHelper.startPage(page, PaginationConstant.PAGE_SIZE);
            List<Course_topic> topics=courseservice.selectbydate_topic_noindex(course_name);
            PageInfo<Course_topic> pageInfo=new PageInfo<>(topics);
            model.addAttribute("pageinfo",pageInfo);
            model.addAttribute("typename","全部课程");
            model.addAttribute("course_name",course_name);
        }
        model.addAttribute("type_id",id);

        return "student/course/coursetopic_type_date";
    }

    //跳转到我的pdf管理界面
    @RequestMapping("/stu/course/pdf/list")
    public String pdf_list(HttpSession session,Model model)
    {
        User user=(User)session.getAttribute("loginuser");
        List<Course_data> datas=courseservice.selectbyuserid_data(user.getId());
        model.addAttribute("datas",datas);
        List<Course_topic> topics=courseservice.selectbytopiclist(user.getId(),"");
        model.addAttribute("topics",topics);
        return "student/course/coursepdf_management";
    }

    //跳转到pdf添加界面
    @RequestMapping("/stu/course/pdf/add")
    public String pdf_add(HttpSession session,Model model)
    {
        User user=(User)session.getAttribute("loginuser");
        List<Course_topic> topics=courseservice.selectbytopiclist(user.getId(),"");
        model.addAttribute("topics",topics);
        return "student/course/coursepdf_add";
    }

    //pdf文件上传
    @RequestMapping("/stu/course/pdf/addsubmit")
    public String pdf_addsubmit(HttpSession session,Course_data data,MultipartFile pdf_dto)
    {
        logger.info("============>文件上传");
        User user=(User)session.getAttribute("loginuser");
        //上传图片和视频并且获得路径
        String pdf=courseservice.upload(pdf_dto);

        data.setPdf(pdf);
        data.setUser_id(user.getId());
        courseservice.insertintocourse_data(data);
        return "common/success";
    }

    //在修改pdf资料前先获得信息
    @RequestMapping("/stu/course/pdf/getinformation")
    public String pdf_getinformation(Integer id,HttpSession session,Model model)
    {
        User user=(User)session.getAttribute("loginuser");
        List<Course_topic> topics=courseservice.selectbytopiclist(user.getId(),"");
        model.addAttribute("topics",topics);
        //通过主键id获得pdf信息
        Course_data data=courseservice.selectbyidcourse_data(id);
        model.addAttribute("data",data);
        return "student/course/coursepdf_update";
    }

    //提交pdf修改的信息到数据库
    @RequestMapping("/stu/course/pdf/updatesubmit")
    public String pdf_updatesubmit(Course_data data,MultipartFile pdf_dto)
    {
        logger.info("============>文件上传");
        //上传图片和视频并且获得路径
        String pdf=courseservice.upload(pdf_dto);
        data.setPdf(pdf);

        courseservice.updateintopdf(data);
        return "common/success";
    }

    //完成pdf删除功能
    @RequestMapping("/stu/course/pdf/delete")
    public String pdf_delete(Integer id)
    {
        courseservice.deletebyidcourse_data(id);
        return "common/success";
    }

    //播放本地视频，由于视频上传到云端，这里的方法失效
    @RequestMapping("/course/playvideo/{id}")
    public void playvideo(@PathVariable("id")Integer id, OutputStream outputStream)
    {
        //通过课程的id号查出该课程的视频
        String path=courseservice.selectbyvideo(id);
        courseservice.showmedia(path,outputStream);
    }

    //下载本地课程视频，由于视频上传到云端，这里的方法失效
    @RequestMapping("/course/download/{id}")
    public void download(@PathVariable("id") Integer id, HttpServletResponse response)throws UnsupportedEncodingException
    {
        //通过课程的id号查出该课程的视频
        String path=courseservice.selectbyvideo(id);
        File file = new File(path);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode("视频.mp4","UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}
